<template>
  <ScrollContainer class="pr-4" v-loading="loading" :loading-tip="t('common.loadingText')">
    <div class="flex justify-around w-1/3 m-auto">
      <!-- <a-button @click="handleResetFields">重置</a-button> -->
      <a-button type="primary" @click="customSubmitFunc">保存</a-button>
    </div>
    <BasicForm @register="registerForm">
      <template #overallSituationSet>
        <a-button :type="dataRef.rules ? 'primary' : 'default'" @click="handleOverallSituationSet">
          <SettingOutlined title="配置" />
        </a-button>
      </template>
    </BasicForm>
    <GlobalSettingsDrawer @register="registerDrawer" @success="handleSuccess" />
  </ScrollContainer>
</template>

<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { ref, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { ScrollContainer } from '/@/components/Container';
  import { formSchema } from './flowEdit.data';
  import { useDrawer } from '/@/components/Drawer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useFlowStore } from '/@/store/modules/flow';
  import { SettingOutlined } from '@ant-design/icons-vue';
  const { t } = useI18n();
  import {
    getAdminFlowGetWorkflowProps,
    getMyflowGenerateWorkflowString,
    getAdminUpdateWorkflowProps,
  } from '/@/api/flowManage/flowManage';
  import GlobalSettingsDrawer from './globalSettingsDrawer/GlobalSettingsDrawer.vue';
  import { isArray } from '/@/utils/is';

  const props = defineProps({
    formCode: {
      type: String as PropType<string>,
      default: '',
    },
    typeCode: {
      type: String as PropType<string>,
      default: '',
    },
    eleId: {
      type: String as PropType<string>,
      required: false,
      default: '',
    },
  });
  const useFlow = useFlowStore();
  const { createMessage } = useMessage();
  const loading = ref(false);
  const dataRef = ref<any>({});
  const customSubmitFunc = async () => {
    const myflow: any = $.myflow;
    // const myflow: any = $(props.eleId);
    console.log('myflow', myflow);
    const flowJson = myflow.getJson();
    // const flowString = myflow.getWorkflow();
    console.log({ flowJson });
    loading.value = true;
    try {
      const serverName = window.location.hostname;
      const flowStringRecord = await getMyflowGenerateWorkflowString({
        flowJson: flowJson,
        serverName: serverName,
      });
      const flowString = flowStringRecord.flowString;
      console.log('flowString', flowString);
      const values = await validate();
      let formdata = Object.assign({}, dataRef.value, values);
      if (isArray(formdata.rules)) {
        formdata.rules = JSON.stringify(formdata.rules);
      }
      for (let v in formdata) {
        if (formdata[v] === true) {
          formdata[v] = '1';
        }
        if (formdata[v] === false) {
          formdata[v] = '0';
        }
      }
      delete formdata.dirTree;
      formdata.flowJson = flowJson;
      formdata.flowString = flowString;
      formdata.typeCode = props.typeCode;

      // 后端接收的是msgProp
      formdata.msgProp = formdata.msgProps;
      delete formdata.msgProps;
      // TODO custom api
      console.log('formdata', formdata);

      const res = await getAdminUpdateWorkflowProps(formdata);
      // emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
      createMessage.success('操作成功');
      fetch();
    } catch (err) {
      console.log(err);
      loading.value = false;
    } finally {
      loading.value = false;
    }
  };
  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
    submitFunc: customSubmitFunc,
  });
  const handleResetFields = () => {
    resetFields();
  };

  const fetch = async () => {
    console.log('props.typeCode', props.typeCode);
    handleResetFields();
    if (!props.typeCode) return;
    try {
      const res = await getAdminFlowGetWorkflowProps({ typeCode: props.typeCode });
      dataRef.value = res;
      console.log('流程详情', res);
      if (typeof res === 'object') {
        useFlow.setFlowEdit(dataRef.value);
        setFieldsValue({ ...dataRef.value });
        updateSchema([
          {
            field: 'dirCode',
            componentProps: {
              showSearch: true,
              treeNodeFilterProp: 'name',
              //mode: 'multiple',
              fieldNames: { label: 'name', value: 'code', key: 'code' },
              getPopupContainer: () => document.body,
              treeData: dataRef.value?.dirTree || [],
            },
          },
        ]);
      } else {
        useFlow.setFlowEdit({});
      }
    } catch (err) {
      console.log(err);
    }
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const handleOverallSituationSet = () => {
    openDrawer(true, {
      rules: dataRef.value.rules,
      formCode: props.formCode,
      typeCode: props.typeCode,
    });
  };
  const handleSuccess = ({ rules }) => {
    dataRef.value.rules = rules;
  };

  onMounted(() => {
    setTimeout(() => {
      fetch();
    });
  });
</script>
